# -*- coding: utf-8 -*-
from flask import request, Flask
import logging
from models import Proxy
import logging.handlers
from logging import Formatter

logger = logging.getLogger(__name__)

app = Flask(__name__)

@app.route('/deleteproxy', methods=['GET'])
def deleteproxy():
    address = request.remote_addr
    query = Proxy.select().where(Proxy.address==address)
    if query.exists():
        Proxy.delete().where(Proxy.address==address).execute()
        logger.info('deleted proxy : %s ' % address)
    else:
        logger.error('proxy do not exists : %s' % address)
    return 'OK'

@app.route('/deletemanually/<address>', methods=['GET'])
def deletemanually(address):
    query = Proxy.select().where(Proxy.address==address)
    if query.exists():
        Proxy.delete().where(Proxy.address==address).execute()
        logger.info('deleted proxy : %s ' % address)
    else:
        logger.error('proxy do not exists : %s' % address)
    return 'OK'

@app.route('/addproxy/<vps>', methods=['GET'])
def addproxy(vps):
    address = request.remote_addr
    Proxy(address=address, vps=vps).save()
    return 'OK'

@app.route('/getproxy', methods=['GET'])
def getproxy():
    query = Proxy.select()
    ips = ['http://%s:30000' % proxy.address for proxy in query]
    return '\n'.join(ips)

def init_log(app):
    # logging初始化工作
    root_logger = logging.getLogger()
    if app.config.get('DEBUG'):
        root_logger.setLevel(logging.DEBUG)
    else:
        root_logger.setLevel(logging.INFO)

    # nor的初始化工作

    # 添加TimedRotatingFileHandler到nor
    # 定义一个1天换一次log文件的handler
    filehandler = logging.handlers.TimedRotatingFileHandler(
            "log/vps.log", 'D', 1, 0)
    filehandler.setFormatter(Formatter(
        '%(asctime)s %(levelname)s: %(message)s '
            '[in %(pathname)s:%(lineno)d]'
            ))
    # 设置后缀名称，跟strftime的格式一样
    filehandler.suffix = "%Y%m%d-%H%M.log"
    root_logger.addHandler(filehandler)

if __name__ == '__main__':
    init_log(app)
    app.run(host='0.0.0.0', port=5000)
